﻿
namespace ConsoleApp3
{
    //泛型协变和逆变

    //泛型协变
    interface IAnimal
    {
        void Sound();
    }
    class Dog : IAnimal
    {
        public void Sound()
        {
            Console.WriteLine("汪汪汪！");
        }
    }
    class Cat : IAnimal
    {
        public void Sound()
        {
            Console.WriteLine("喵喵喵!");
        }
    }

    //泛型逆变
    delegate void AnimalSoundAction<in T>(T animal);

    internal class Program
    {
        //泛型逆变
        static void Sound(IAnimal animal)
        {
            Console.WriteLine("动物叫!");
        }

        public static void Main(string[] args)
        {
            //泛型协变
            List<IAnimal> animals = new List<IAnimal>
            {
                new Cat(),
                new Dog(),
            };
            foreach (IAnimal animal in animals)
            {
                animal.Sound();
            }

            //泛型逆变
            AnimalSoundAction<IAnimal> animalSound = Sound;
            IAnimal dog = new Dog();

            animalSound(dog);
        }
    }
}